package com.echo.yixiaowu.feature.player.video

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.echo.yixiaowu.R
import com.echo.yixiaowu.feature.player.MediaViewModel
import com.echo.yixiaowu.feature.components.ActionIcon
import com.echo.yixiaowu.feature.components.UserAvatarComment
import com.echo.yixiaowu.feature.player.MediaPageIntent

/**
 * 可展开/收起的详情组件
 * @param title 标题
 * @param playCount 播放数
 * @param commentCount 评论数
 * @param publishTime 发布时间
 * @param content 详情内容
 * @param modifier Modifier
 */
@Composable
fun VideoExpandableDetails(
    title: String,
    playCount: String,
    commentCount: String,
    publishTime: String,
    content: String,
    isExpanded: Boolean,
    onIsExpanded: (Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(Color.White)
            .padding(horizontal = 16.dp, vertical = 12.dp)
    ) {
        // 第一行: 标题、图标
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable { onIsExpanded(!isExpanded) },
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(
                text = title,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
                maxLines = if (isExpanded) Int.MAX_VALUE else 1,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier
                    .animateContentSize(animationSpec = tween(200))
                    .weight(1f)
            )
            // 根据 isExpanded 状态显示不同图标
            Icon(
                imageVector = if (isExpanded) ImageVector.vectorResource(R.drawable.ic_keyboard_arrow_up)
                else ImageVector.vectorResource(R.drawable.ic_keyboard_arrow_down),
                contentDescription = if (isExpanded) "收起" else "展开"
            )
        }
        Spacer(modifier = Modifier.height(8.dp))
        // 第二行: 播放数、评论数、发布时间
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(16.dp) // 元素间的间距
        ) {
            Text(
                text = "播放 $playCount",
                style = MaterialTheme.typography.bodySmall,
                color = Color.Gray
            )
            Text(
                text = "评论 $commentCount",
                style = MaterialTheme.typography.bodySmall,
                color = Color.Gray
            )
            Text(
                text = "发布于 $publishTime",
                style = MaterialTheme.typography.bodySmall,
                color = Color.Gray
            )
        }

        // 动画容器
        AnimatedVisibility(
            visible = isExpanded,
            // 定义进入和退出的动画效果
            enter = fadeIn(animationSpec = tween(200)) + expandVertically(animationSpec = tween(400)),
            exit = fadeOut(animationSpec = tween(200)) + shrinkVertically(animationSpec = tween(400))
        ) {
            Column {
                Spacer(modifier = Modifier.height(12.dp))
                Text(
                    text = content,
                    style = MaterialTheme.typography.bodyMedium,
                    lineHeight = 22.sp // 增加行高，提升可读性
                )
            }
        }
    }
}

@Composable
fun VideoFeatureRow(
    isFavorite: Boolean,
    isLiked: Boolean,
    isDisliked: Boolean,
    onIntent: (MediaPageIntent) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
    ) {

        ActionIcon(modifier = Modifier.weight(1f),
            imageVector = ImageVector.vectorResource(R.drawable.ic_thumb_up),
            contentDescription = "点赞",
            tint = toggleColor(isLiked),
            onClick = { onIntent(MediaPageIntent.ClickMediaLike(isLiked)) })

        ActionIcon(modifier = Modifier.weight(1f),
            imageVector = ImageVector.vectorResource(R.drawable.ic_not_like),
            contentDescription = "踩",
            tint = toggleColor(isDisliked),
            onClick = { onIntent(MediaPageIntent.ClickMediaDislike(isDisliked)) })

        ActionIcon(modifier = Modifier.weight(1f),
            imageVector = ImageVector.vectorResource(R.drawable.ic_star),
            contentDescription = "收藏",
            tint = toggleColor(isFavorite),
            onClick = { onIntent(MediaPageIntent.ClickMediaFavorite(isFavorite)) })

        ActionIcon(modifier = Modifier.weight(1f),
            imageVector = ImageVector.vectorResource(R.drawable.ic_share),
            contentDescription = "分享",
            tint = Color.Gray,
            onClick = {})
    }
}

val toggleColor: (Boolean) -> Color = { currentState ->
    if (currentState) Color.Red else Color.Gray
}

/**
 * 视频推荐列表
 * @param title 视频标题
 * @param author 作者
 * @param views 观看次数
 * @param commentCount 评论数量
 * @param onMoreClick “更多”菜单的点击回调
 */
@Composable
fun VideoSuggestItem(
    title: String, author: String, views: String, commentCount: String, onMoreClick: () -> Unit
) {
    val interactionSource = remember { MutableInteractionSource() }

    Column(modifier = Modifier
        .fillMaxWidth()
        .clickable {
            //todo 点击事件
        }
        .padding(horizontal = 12.dp, vertical = 8.dp)) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧封面图
            Image(
                painter = painterResource(R.drawable.image2),
                contentDescription = "Video Thumbnail",
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .weight(0.35f)
                    .aspectRatio(16 / 9f)
                    .clip(RoundedCornerShape(8.dp))
                    .align(Alignment.CenterVertically)
            )

            // 右侧信息区
            Column(
                modifier = Modifier.weight(0.65f),
            ) {
                // 标题
                Text(
                    modifier = Modifier.padding(bottom = 16.dp, start = 2.dp),
                    text = title,
                    style = MaterialTheme.typography.labelLarge,
                    fontWeight = FontWeight.Normal,
                    maxLines = 2, // 最多两行，超出则显示省略号
                    overflow = TextOverflow.Ellipsis,
                    lineHeight = 22.sp
                )

                // 作者信息
                Text(
                    text = author,
                    style = MaterialTheme.typography.bodyMedium,
                    color = Color.Gray,
                    modifier = Modifier.padding(start = 2.dp)
                )

                // 播放量和时间
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(2.dp)
                ) {
                    Icon(
                        imageVector = ImageVector.vectorResource(R.drawable.ic_play_arrow),
                        contentDescription = "Views",
                        tint = Color.Gray,
                        modifier = Modifier.size(14.dp)
                    )
                    Text(
                        text = "${views}观看",
                        style = MaterialTheme.typography.bodySmall,
                        color = Color.Gray
                    )
                    Icon(
                        imageVector = ImageVector.vectorResource(R.drawable.ic_comment),
                        contentDescription = "Comment",
                        tint = Color.Gray,
                        modifier = Modifier
                            .size(14.dp)
                            .padding(start = 4.dp)
                    )
                    Text(
                        text = commentCount,
                        style = MaterialTheme.typography.bodySmall,
                        color = Color.Gray,
                        modifier = Modifier.weight(1f)
                    )
                    // 右侧的“更多”菜单图标
                    Icon(
                        imageVector = ImageVector.vectorResource(R.drawable.ic_more_vert),
                        contentDescription = "More options",
                        tint = Color.Gray,
                        modifier = Modifier
                            .clip(CircleShape)
                            .clickable(
                                interactionSource = interactionSource,
                                indication = null,
                                onClick = onMoreClick
                            )
                    )
                }
            }
        }
    }
}

@Composable
fun CardDetailComment(page: Int, viewModel: MediaViewModel = viewModel()) {
    val commentUiState by viewModel.commentUiState.collectAsStateWithLifecycle()
    val commentList = commentUiState.commentList
    var isHotComment by remember { mutableStateOf(true) }

    LaunchedEffect(page) {
        viewModel.processIntent(MediaPageIntent.LoadCommentData("1"))
    }
    LazyColumn(
        modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        item {
            Row(
                modifier = Modifier
                    .padding(vertical = 8.dp)
                    .padding(horizontal = 12.dp)
            ) {
                Text(
                    text = if (isHotComment) "热门评论" else "最新评论",
                    modifier = Modifier.weight(1f)
                )
                Text(text = if (isHotComment) "按热度" else "按时间",
                    modifier = Modifier.clickable {
                        isHotComment = !isHotComment
                    })
            }
        }
        items(items = commentList, key = { comment -> comment.id }) { comment ->
            UserAvatarComment(modifier = Modifier.padding(horizontal = 8.dp),
                commentData = comment,
                likeColor = if (comment.isLiked) Color.Red else Color.Gray,
                onLikeClick = {
                    viewModel.processIntent(
                        MediaPageIntent.ClickCommentLike(comment.id)
                    )
                },
                dislikeColor = if (comment.isDisliked) Color.Blue else Color.Gray,
                onDislikeClick = {
                    viewModel.processIntent(
                        MediaPageIntent.ClickCommentDislike(comment.id)
                    )
                })
            HorizontalDivider(
                modifier = Modifier.padding(top = 10.dp),
                color = Color.Gray.copy(alpha = 0.1f),
                thickness = 1.dp
            )
        }
    }
}
